import { useAuthStore } from '@/stores/auth'

export function setupInterceptors(instance) {
    // 响应拦截器 - 处理token过期
    instance.interceptors.response.use(
        response => response,
        async error => {
            const originalRequest = error.config
            const authStore = useAuthStore()

            // 如果是401错误且不是登录请求，尝试刷新token
            if (error.response?.status === 401 &&
                !originalRequest._retry &&
                !originalRequest.url.includes('/login')) {
                originalRequest._retry = true

                try {
                    // 重新获取token
                    await authStore.fetchToken()
                    // 重试原始请求
                    return instance(originalRequest)
                } catch (refreshError) {
                    // 刷新token失败
                    authStore.clearToken()
                    return Promise.reject(refreshError)
                }
            }

            return Promise.reject(error)
        }
    )
}